import type { AIProvider } from './types.js';
import { ZhipuAIProvider } from './zhipu-provider.js';
import { OpenAIProvider } from './openai-provider.js';

// AI提供商工厂
export class AIProviderFactory {
  private static providers: Map<string, () => AIProvider> = new Map([
    ['zhipu', () => new ZhipuAIProvider()],
    ['openai', () => new OpenAIProvider()],
  ]);

  // 根据模型名称获取提供商
  static getProvider(model?: string): AIProvider {
    const targetModel = model || process.env.AI_MODEL || 'gpt-3.5-turbo';

    // 根据模型前缀判断提供商
    if (targetModel.startsWith('glm-')) {
      return this.createProvider('zhipu');
    }

    if (targetModel.startsWith('gpt-') || targetModel.startsWith('text-')) {
      return this.createProvider('openai');
    }

    // 默认使用OpenAI
    return this.createProvider('openai');
  }

  // 根据提供商名称创建实例
  static createProvider(providerName: string): AIProvider {
    const providerFactory = this.providers.get(providerName);

    if (!providerFactory) {
      throw new Error(`不支持的AI提供商: ${providerName}`);
    }

    return providerFactory();
  }

  // 获取所有可用的提供商
  static getAvailableProviders(): AIProvider[] {
    return Array.from(this.providers.keys()).map((name) =>
      this.createProvider(name)
    );
  }

  // 获取第一个已配置的提供商
  static getConfiguredProvider(): AIProvider {
    const providers = this.getAvailableProviders();

    for (const provider of providers) {
      if (provider.isConfigured()) {
        console.log(`使用AI提供商: ${provider.getName()}`);
        return provider;
      }
    }

    throw new Error('没有找到已配置的AI提供商，请检查环境变量配置');
  }

  // 注册新的提供商
  static registerProvider(name: string, factory: () => AIProvider): void {
    this.providers.set(name, factory);
  }

  // 获取提供商配置状态
  static getProviderStatus(): Array<{
    name: string;
    configured: boolean;
    provider: string;
  }> {
    return Array.from(this.providers.keys()).map((name) => {
      const provider = this.createProvider(name);
      return {
        name: provider.getName(),
        configured: provider.isConfigured(),
        provider: name,
      };
    });
  }
}
